<?php

namespace app\controller\open;

use app\controller\api\CaptchaController;
use app\controller\bossManager\WebBossController;
use app\exception\ErrnoPlus;
use app\validate\OpenLoginValidate;
use share\service\CaptchaService;
use share\service\UserBaseService;
use share\service\UserPassService;
use share\utils\Helper;
use think\Log;

class LoginController extends BaseOpenController
{
    protected $beforeActionList = [
    ];

    public function initValidate()
    {
        $this->validate = new OpenLoginValidate();
    }

    public function login_by_password_action()
    {
        $aesData = $this->check('decode');
        $params = WebBossController::decodeAESData($aesData['key'], config('AES_IV'), $aesData['smData']);
        $input = $this->check('loginByPass', $params);
        $ip = $this->request->ip();
        if (!CaptchaController::checkHash($input['hash'])) {
            trace('captcha hash format error ip: ' . $ip, Log::ERROR);
            return self::fail("invaild request", ErrnoPlus::CAPTCHA_INVALID_REQUEST);
        }
        if (!CaptchaService::check($input['hash'], $input['captcha'])) {
            return self::fail("captcha code error", ErrnoPlus::CAPTCHA_CODE_ERROR);
        }
        if(isset($input['email']) && Helper::checkEmailFormat($input['email'])){
            $userInfo = UserBaseService::getByEmail($input['email'],['vendor'=> $input['vendor']]);
        }
        else{
            $userInfo = UserBaseService::getByPhone($input['phone'],['vendor'=> $input['vendor']]);
        }
        if(empty($userInfo)){
            return self::fail("account is not exist",ErrnoPlus::USER_NOT_EXISTS);
        }
        
        if(!UserPassService::comparePass($input['password'],$userInfo['user_id'])){
            return self::fail("account or password error",ErrnoPlus::USER_NOT_EXISTS);
        }

        $token = self::authToken($userInfo);

        return self::ok(['token' => $token]);
    }
}
